import { useEffect } from "react";
import { Space, Divider, Table, Popconfirm, Image as AntdImage, Tag, Row, Col, Radio, Avatar, message } from "antd";
import { Card as SemiCard, ButtonGroup, Button, List } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh, IconPlus, IconEdit, IconHome, IconEyeOpened } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import Jdenticon from "react-jdenticon";

import useDeveloper from "../../hooks/resource/useDeveloper";

import AddDeveloperModal from "../../components/resources/developer.add";

import { FindProgramers, FindTesters } from "../../_graphql/developer";

const { Column } = Table;

const DeveloperPage = () => {
    const { windowInnerHeight, graphqlFetchPlatform } = useModel("global");
    const { kuboUrl } = useModel("kubo");
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent } = useModel("global.modal");
    const { dataLoading, loadDevelopers, developers } = useDeveloper();
    const { submitLoading, changeDeveloperStatus } = useDeveloper();

    const state = useReactive({
        loading: false,
        submitLoading: false,
        memberLoading: false,
        selectedDeveloper: {},
        groups: [
            { label: "开发人员", value: "开发人员" },
            { label: "测试人员", value: "测试人员" },
        ],
        selectedGroup: "开发人员",
        members: [],
    });

    useEffect(() => {
        loadDevelopers();
    }, []);

    useEffect(() => {
        if (developers?.length > 0) {
            let selectedDeveloper = developers.find((item) => item.oiUscc === state.selectedDeveloper?.oiUscc);
            !selectedDeveloper && (selectedDeveloper = developers[0]);
            state.selectedDeveloper = selectedDeveloper;
        }
    }, [developers]);

    const addDeveloper = () => {
        setModalTitle("添加开发商");
        setModalWidth(500);
        setModalComponent(<AddDeveloperModal developers={state.developers} reloadData={loadDevelopers} />);
        setModalVisible(true);
    };

    const handleChangeStatus = async () => {
        await changeDeveloperStatus(state.selectedDeveloper.oiUscc, !state.selectedDeveloper.oadStat, (res) => {
            if (res) {
                message.success("成功更新开发组织状态");
                loadDevelopers();
            }
        });
    };

    const loadMembers = async () => {
        state.memberLoading = true;
        let res;
        switch (state.selectedGroup) {
            case "开发人员":
                res = await graphqlFetchPlatform({ query: FindProgramers, variables: { oiUscc: state.selectedDeveloper.oiUscc } });
                state.members = res?.a?.nodes?.map((item) => ({ status: item.b.pdStat, ...item.b.c }));
                break;
            case "测试人员":
                res = await graphqlFetchPlatform({ query: FindTesters, variables: { oiUscc: state.selectedDeveloper.oiUscc } });
                state.members = res?.a?.nodes?.map((item) => ({ status: item.b.ptStat, ...item.b.c }));
                break;
            default:
                break;
        }
        state.memberLoading = false;
    };

    useEffect(() => {
        state.selectedDeveloper?.oiUscc && loadMembers();
    }, [state.selectedDeveloper, state.selectedGroup]);

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;

    return (
        <div style={{ padding: 10 }}>
            <Row gutter={10}>
                <Col span={6}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>开发组织列表</span>}
                        headerStyle={{ padding: "10px 14px" }}
                        shadows="always"
                        headerExtraContent={
                            <ButtonGroup>
                                <Button icon={<IconPlusCircle />} onClick={addDeveloper}></Button>
                                <Button icon={<IconRefresh />} onClick={loadDevelopers}></Button>
                            </ButtonGroup>
                        }
                        bordered={false}
                        bodyStyle={{ padding: 1, height: cardBodyHeight - 2, overflow: "auto" }}
                    >
                        <List
                            loading={dataLoading}
                            dataSource={developers}
                            renderItem={(item, index) => (
                                <List.Item
                                    key={index}
                                    style={{ padding: "12px 12px 12px 12px" }}
                                    className={`list-item list-item-state ${state.selectedDeveloper?.oiUscc === item?.oiUscc ? "list-selected-item" : ""}`}
                                    header={
                                        <div style={{ padding: 0, margin: 0 }}>
                                            {item.oadStat ? <Tag color="#87d068">正常</Tag> : <Tag color="#f50">禁用</Tag>}
                                        </div>
                                    }
                                    main={
                                        <div title={item.oiUscc + " - " + (item.oiPrin || "") + (item.oiCity || "") + (item.oiDist || "")}>
                                            {item?.oiFuna || "-"}
                                        </div>
                                    }
                                    onClick={() => (state.selectedDeveloper = item)}
                                ></List.Item>
                            )}
                        />
                    </SemiCard>
                </Col>
                <Col span={18}>
                    <SemiCard
                        title={
                            <span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>
                                <Radio.Group
                                    onChange={(e) => (state.selectedGroup = e.target.value)}
                                    value={state.selectedGroup}
                                    options={state.groups}
                                    optionType="button"
                                    buttonStyle="solid"
                                />
                            </span>
                        }
                        headerStyle={{ padding: "10px 14px" }}
                        headerExtraContent={
                            <ButtonGroup>
                                {state.selectedDeveloper.oiUscc && (
                                    <Popconfirm
                                        title={`确认要改变开发组织的状态吗?`}
                                        okButtonProps={{ loading: submitLoading }}
                                        placement="topRight"
                                        onConfirm={handleChangeStatus}
                                    >
                                        {state.selectedDeveloper?.oadStat ? <Button type="danger">禁用</Button> : <Button>启用</Button>}
                                    </Popconfirm>
                                )}
                            </ButtonGroup>
                        }
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto" }}
                    >
                        <Table
                            loading={state.loading}
                            dataSource={state.members}
                            rowKey="miIdno"
                            bordered
                            size="small"
                            pagination={false}
                            scroll={{ y: cardBodyHeight - 40 }}
                        >
                            <Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
                            <Column
                                title="头像"
                                dataIndex="miAvat"
                                align="center"
                                width={100}
                                render={(_, r, i) => {
                                    let avatarUrl = kuboUrl && _ ? kuboUrl + _ : <Jdenticon size="24" value={r.miName || ""} />;
                                    return <Avatar src={avatarUrl} />;
                                }}
                            />
                            <Column title="姓名" dataIndex="miName" align="left" />
                            <Column title="性别" dataIndex="miRoge" align="center" width={80} />
                            <Column title="手机号" dataIndex="miPhon" align="center" width={160} />
                            <Column title="身份证号" dataIndex="miIdno" align="center" width={180} />
                            <Column
                                title="所在地区"
                                dataIndex="miPrin"
                                align="left"
                                render={(_, r) => (r.miPrin || "") + (r.miCity || "") + (r.miDist || "")}
                            />
                            <Column title="加入方式" dataIndex="miJoty" align="center" width={120} />
                            <Column
                                title="审核状态"
                                dataIndex="status"
                                align="center"
                                width={100}
                                render={(_, r) => (_ ? <Tag color="#87d068">正常</Tag> : <Tag color="#f50">已禁用</Tag>)}
                            />
                        </Table>
                    </SemiCard>
                </Col>
            </Row>
        </div>
    );
};

export default DeveloperPage;
